import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_demo/tmac/widget/CircleWidget.dart';

class SimpleBannerWidget extends StatefulWidget {
  Color selectColor;
  final Color unSelectColor;
  final List<String> images;
  double selectIndicatorWidth;
  double selectIndicatorHeight;
  double unSelectIndicatorWidth;
  double unSelectIndicatorHeight;

  SimpleBannerWidget(
      {Key key,
      @required this.images,
      this.unSelectIndicatorWidth = 3.5,
      this.unSelectIndicatorHeight = 3.5,
      this.selectIndicatorHeight = 3.5,
      this.selectIndicatorWidth = 15,
      this.selectColor = Colors.blue,
      this.unSelectColor = Colors.grey})
      : assert(images.length > 0);

  @override
  State<StatefulWidget> createState() {
    return SimpleBannerState();
  }
}

class SimpleBannerState extends State<SimpleBannerWidget> {
  Timer timer;
  int currentIndicatorIndex = 0;
  int currentPageViewIndex = 0;

  List<Widget> indicatorWidgets = [];
  var map = new Map();
  Widget selectIndicator;
  Widget unSelectIndicator;
  PageController _pageController;
  int length;

  //创建指示器
  void buildIndicator() {
    selectIndicator = CircleWidget(
      color: widget.selectColor,
      width: widget.selectIndicatorWidth,
      height: widget.selectIndicatorHeight,
    );
    unSelectIndicator = CircleWidget(
      color: widget.unSelectColor,
      width: widget.unSelectIndicatorWidth,
      height: widget.unSelectIndicatorHeight,
    );
    for (int i = 0; i < widget.images.length; i++) {
      map[i] = i == currentIndicatorIndex;
    }
    for (var item in map.values) {
      indicatorWidgets.add(item ? selectIndicator : unSelectIndicator);
    }
  }

  //自动切换指示器设置
  void setIndicatorWidget() {
    currentIndicatorIndex++;
    if (currentIndicatorIndex >= widget.images.length) {
      currentIndicatorIndex = 0;
    }
    for (int i = 0; i < widget.images.length; i++) {
      map[i] = i == currentIndicatorIndex;
    }

    map.forEach((key, value) {
      indicatorWidgets[key] = value ? selectIndicator : unSelectIndicator;
    });
  }

  void initPageView() {
    _pageController = PageController(initialPage: currentPageViewIndex);
    length = widget.images.length;
  }

  void setPageView() {
    currentPageViewIndex++;
    _pageController.animateToPage(
      currentPageViewIndex,
      duration: Duration(milliseconds: 300),
      curve: Curves.linear,
    );
  }

  /// 点击到图片的时候取消定时任务
  _cancelTimer() {
    if (timer != null) {
      timer.cancel();
      timer = null;
      // _initTimer();
    }
  }

  /// 切换页面，并刷新小圆点
  _changePage() {
    Timer(Duration(milliseconds: 350), () {
      _pageController.jumpToPage(currentPageViewIndex);
    });
  }

  Widget buildPageView() {
    return PageView.builder(
      physics: NeverScrollableScrollPhysics(),
      controller: _pageController,
      onPageChanged: (index) {
        setState(() {
          // currentPageViewIndex = index;
          // if (index == 0) {
          //   currentPageViewIndex = length;
          //   _changePage();
          // }
        });
      },
      itemBuilder: (context, index) {
        return GestureDetector(
          onPanDown: (details) {
            //_cancelTimer();
          },
          onTap: () {
            Scaffold.of(context).showSnackBar(
              SnackBar(
                content: Text('当前 page 为 ${index % length}'),
                duration: Duration(milliseconds: 500),
              ),
            );
          },
          child: Image.network(
            widget.images[index % length],
            fit: BoxFit.cover,
          ),
        );
      },
    );
  }

  @override
  void initState() {
    super.initState();
    initPageView();
    buildIndicator();

    timer = Timer.periodic(Duration(seconds: 4), (timer) {
      setState(() {
        setIndicatorWidget();
        setPageView();
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    timer?.cancel();
    timer = null;
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: <Widget>[
        Center(child: buildPageView()),
        Align(
          alignment: Alignment.bottomCenter,
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Wrap(
                    spacing: 2,
                    children: indicatorWidgets,
                  ),
                  Padding(padding: EdgeInsets.only(bottom: 10))
                ],
              ),
            ],
          ),
        ),

        //底部指示器
      ],
    );
  }
}
